<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 7/8/17
 * Time: 8:32 AM
 */
declare(strict_types=1);


namespace application\module\admin\addon\rbca\model;


use application\module\admin\addon\model\AddonModel;

class RoleAccessModel extends AddonModel
{
    protected function tableName()
    {
        return 'rel_role_access';
    }

    protected function tablePrefix()
    {
        return 'ws_auth_';
    }

    protected function struct(): string
    {
        $prefix = $this->tablePrefix();
        return "  `rid` int(10) unsigned NOT NULL COMMENT 'role id',
  `aid` int(10) unsigned NOT NULL COMMENT 'access id',
  PRIMARY KEY (`rid`,`aid`),
  KEY `role_auth2` (`aid`),
  CONSTRAINT `aid` FOREIGN KEY (`aid`) REFERENCES `{$prefix}access` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `rid` FOREIGN KEY (`rid`) REFERENCES `{$prefix}role` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
";
    }

    /**
     * 查询角色
     * @param int $rid
     * @return array
     */
    public function getRoleAccesses(int $rid): array
    {
        $rid = intval($rid);
        $list = $this->fields("a.*,ifnull(rra.aid,0) as access,{$rid} as rid")
            ->table('{{access}} a')
            ->leftOuterJoin("{{rel_role_access}}  rra on rra.aid = a.id and rra.rid = $rid")
            ->select();
        return $list;
    }

}